package com.hrm.action;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hrm.entity.User;
import com.hrm.entity.UserLog;
import com.hrm.service.UserLogService;
public class ActionUtil {
	private static final Log log = LogFactory.getLog(ActionUtil.class); 

	private static String getRemoteIP(HttpServletRequest request) {
		String ipAddress = null;
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
	
	public static void insertLog(HttpServletRequest request,String msgType,String msg,UserLogService userLogService){
		User user = (User) request.getSession().getAttribute("user");
		UserLog uLog = new UserLog();
		uLog.setMsg(msg);
		uLog.setMsgType(msgType);
		uLog.setOperationTime(new Date());
		uLog.setUserId(user.getId());
		uLog.setUserIp(getRemoteIP(request));
		if(userLogService.addUserLog(uLog)<0){
			log.error("================================================");
			log.error("insert user operation into user_log failed!please insert below info by yourself:");
			log.error("opertion user info: [id="+user.getId()+",userName="+user.getUserName());
			log.error("opertion_time:"+new Date());
			log.error("msg_type:"+msgType);
			log.error("msg"+msg);
			log.error("================================================");
		}
	}
}
